package com.spic.system.controller;

import com.spic.common.core.constant.UserConstants;
import com.spic.common.core.domain.R;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.core.web.controller.BaseController;
import com.spic.common.core.web.domain.AjaxResult;
import com.spic.common.log.annotation.Log;
import com.spic.common.log.enums.BusinessType;
import com.spic.common.security.annotation.PreAuthorize;
import com.spic.common.security.utils.cache.DeptCacheUtils;
import com.spic.system.api.domain.SysDept;
import com.spic.system.api.dto.DeptDTO;
import com.spic.system.service.BusinessDataScopeService;
import com.spic.system.service.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private BusinessDataScopeService businessDataScopeDBService;
    //调度班组配置文件
    @Value("${ddDeptName}")
    private String ddDeptName;

    @GetMapping("/cache")
    public Map<Long, String> cache()
    {
        List<DeptDTO> list = DeptCacheUtils.getCache();
        return list.stream().collect(Collectors.toMap(DeptDTO::getDeptId, DeptDTO::getDeptName));
    }

    @GetMapping("/cache2")
    public Map<String, Long> cache2()
    {
        List<DeptDTO> list = DeptCacheUtils.getCache();
        return list.stream().filter(item ->
        {
            String ancestors = item.getAncestors();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(ancestors))
            {
                return ancestors.split(",").length == 2;
            }
            else
            {
                return true;
            }
        }
        ).collect(Collectors.toMap(DeptDTO::getDeptName, DeptDTO::getDeptId, (k1,k2) -> k2));
    }

    @GetMapping("/allDeptIds")
    public AjaxResult allDeptIds()
    {
        String deptids = deptService.allDeptIds();
        return AjaxResult.success(deptids);
    }
    /**
     * 获取部门列表
     */

    @GetMapping("/lists/{deptId}")
    public AjaxResult lists(@PathVariable("deptId")Long deptId)
    {
        SysDept sysDept = deptService.selectDeptById(deptId);
        return AjaxResult.success(sysDept);
    }
    /**
     * 获取部门列表
     */
//    @PreAuthorize(hasPermi = "system:dept:list")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        List<SysDept> collect = depts.stream().filter(d -> d.getDeptId()!= 100).collect(Collectors.toList());
        return AjaxResult.success(depts);
    }

    /**
     * 获取1级级部门 列表
     * @param dept
     * @return
     */
    @GetMapping("/listOrg")
    public AjaxResult listOrg(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        List<SysDept> collect1 = depts.stream().filter(d -> d.getDeptId()!= 100).collect(Collectors.toList());
        List<SysDept> collect = collect1.stream().filter(d -> d.getParentId() == 100).collect(Collectors.toList());
        return AjaxResult.success(collect);
    }
    /**
     * 根据部门id查询列表
     * @param deptId
     * @return
     */
    @GetMapping("/listsOrg/{deptId}")
    public AjaxResult listsOrg(@PathVariable("deptId")Long deptId)
    {
        SysDept dept = new SysDept();
        dept.setParentId(deptId);
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 查询调度部门列表
     * @return
     */
    @GetMapping("/listsOrgDd")
    public AjaxResult listsOrgDd()
    {
        SysDept dept = new SysDept();

        dept.setDeptName(ddDeptName);
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }


    /**
     * 查询部门列表（排除节点）
     */
//    @PreAuthorize(hasPermi = "system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext())
        {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
//    @PreAuthorize(hasPermi = "system:dept:query")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }
    /**
     * 获取部门下拉树列表
     */
    @PostMapping("/treeselectList")
    public AjaxResult treeselectList( SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 获取部门下拉树列表APP
     */
    @GetMapping("/treeselect/app")
    public AjaxResult treeselectOfApp(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelectOfApp(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门
     */
    @PreAuthorize(hasPermi = "system:dept:add")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    @PostMapping("/addNoAuth")
    public R<Long> addNoAuth(@Validated @RequestBody SysDept dept)
    {
        SysDept deptByNameAndParentId = deptService.getDeptByNameAndParentId(dept);
        if(deptByNameAndParentId != null) {
            return R.ok(deptByNameAndParentId.getDeptId());
        } else {
            dept.setCreateBy("admin");
            return R.ok(deptService.insertDeptNoAuth(dept));
        }
    }

    /**
     * 修改部门
     */
    @PreAuthorize(hasPermi = "system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(dept.getDeptId()))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize(hasPermi = "system:dept:remove")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }
    /**
     * 获取部门Map
     * key :id
     * value :name
     */

    @GetMapping("/map")
    public AjaxResult map()
    {
        Map<Long,String> map = deptService.map();
        return AjaxResult.success(map);
    }

    /**
     * 通过roleId获取部门
     * @param roleId
     * @return
     */
    @GetMapping("/custom_dept")
    public R<List<Long>> getCustomDeptIds(@RequestParam("roleId") Long roleId){
        List<Long> deptIds = businessDataScopeDBService.customDeptIds(roleId);
        return R.ok(deptIds);
    }

    /**
     * 获取当前部门及子部门
     * @param deptId
     * @return
     */
    @GetMapping("/dept_and_children")
    public R<List<Long>> getDeptAndChildren(@RequestParam("deptId") Long deptId){
        List<Long> deptIds = businessDataScopeDBService.deptAndChildrenIds(deptId);
        return R.ok(deptIds);
    }


    /**
     * 获取当前部名称
     * @param deptId
     * @return
     */
    @GetMapping("/dept_name")
    public R<String> getDeptName(@RequestParam("deptId") Long deptId){
        String deptName = deptService.selectDeptById(deptId).getDeptName();
        return R.ok(deptName);
    }

    /**
     *通过部门id查询部门领导Id
     * @param deptIds
     * @return
     */
    @GetMapping("/getDeptLeaderIdDeptIds")
    public AjaxResult getDeptLeaderIdDeptIds(@RequestParam("deptIds") String deptIds)
    {
        List<Long> list= deptService.selectDeptLeaderIdDeptIds(deptIds);
        return AjaxResult.success(list);
    }

    /**
     * 根据子部门id查询父级部门的名称
     * @param deptId   子部门id
     * @return
     */
    @GetMapping("/getSysDeptBychildenId")
    public AjaxResult getSysDeptBychildenId(@RequestParam("deptId") Long deptId){
        SysDept sysDept = deptService.getSysDeptBychildenId(deptId);
        return AjaxResult.success(sysDept.getDeptName());
    }

}
